<template>
  <div class="test-result">
    <el-card class="result-card">
      <!-- 测试基本信息 -->
      <div class="test-header">
        <h2>{{ test.title }}</h2>
        <div class="test-info">
          <div>总分：{{ result.totalScore }}分</div>
          <div>测试用时：{{ formatDuration(testDuration) }}</div>
        </div>
      </div>

      <template #header>
        <div class="card-header">
          <span>测试结果</span>
          <el-tag 
            :type="result.reviewedBy ? 'success' : 'warning'"
            size="small"
          >
            {{ result.reviewedBy ? '已评审' : '等待评审' }}
          </el-tag>
        </div>
      </template>
      
      <!-- 初步评估结果 -->
      <el-descriptions :column="1" border>
        <el-descriptions-item label="总分">
          {{ result.totalScore }}
        </el-descriptions-item>
        <el-descriptions-item label="评估等级">
          {{ result.level }}
        </el-descriptions-item>
        <el-descriptions-item label="维度得分">
          <div v-if="dimensionScores">
            <div v-for="(score, dimension) in dimensionScores" :key="dimension">
              {{ getDimensionName(dimension) }}: {{ score }}
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="初步分析">
          {{ result.analysis }}
        </el-descriptions-item>
        <el-descriptions-item label="建议">
          <div class="suggestions">
            {{ result.suggestions }}
          </div>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 答题记录 -->
      <div class="answer-record">
        <el-divider>答题记录</el-divider>
        <div v-if="test.questions" class="question-list">
          <div v-for="(question, index) in test.questions" :key="question.id" class="question-item">
            <div class="question-header">
              <span class="question-number">{{ index + 1 }}.</span>
              <span class="question-text">{{ question.questionText }} ({{ question.score }}分)</span>
            </div>
            
            <!-- 选项列表 -->
            <div class="options-list">
              <el-radio-group v-model="answers[question.id]" disabled>
                <el-radio
                  v-for="(option, optIndex) in question.options"
                  :key="optIndex"
                  :label="(optIndex + 1).toString()"
                >
                  {{ String.fromCharCode(65 + optIndex) }}. {{ option }}
                </el-radio>
              </el-radio-group>
            </div>
            
            <!-- 考生答案 -->
            <div class="answer-content">
              <div class="answer-label">考生答案：</div>
              <div class="answer-text">
                {{ answers[question.id] ? String.fromCharCode(64 + parseInt(answers[question.id])) : '未作答' }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 评审信息 -->
      <div v-if="result.reviewedBy" class="review-info">
        <el-divider>心理咨询师评审意见</el-divider>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="评审人">
            {{ result.reviewerName }}
          </el-descriptions-item>
          <el-descriptions-item label="评审时间">
            {{ formatTime(result.reviewTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="评审意见">
            {{ result.reviewComments }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <div v-else class="waiting-review">
        <el-alert
          title="等待心理咨询师评审"
          type="info"
          description="专业的心理咨询师将会对您的测试结果进行评估，并提供个性化的建议。"
          show-icon
          :closable="false"
        />
      </div>

      <!-- 操作按钮 -->
      <div class="actions">
        <el-button type="primary" @click="backToList">返回列表</el-button>
        <el-button 
          type="success" 
          @click="startAIConsultation"
          v-loading="checkingSession"
        >
          <el-icon><ChatRound /></el-icon>
          {{ hasActiveSession ? '继续 AI 咨询' : '开始 AI 咨询' }}
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getTestResult, getTestAnswerRecord } from '../../api/psychological-test'
import { formatTime, formatDuration } from '../../utils/format'
import { ElMessage } from 'element-plus'
import { ChatRound } from '@element-plus/icons-vue'
import { createAIChatSession, getAIChatSessions } from '@/api/ai-chat'

export default {
  name: 'TestResult',
  components: {
    ChatRound
  },
  data() {
    return {
      test: {
        title: '',
        questions: []
      },
      result: {
        id: null,
        totalScore: 0,
        level: '',
        dimensionScores: '',
        analysis: '',
        suggestions: '',
        reviewComments: '',
        reviewerName: '',
        reviewTime: null
      },
      dimensionScores: null,
      answers: {},
      testDuration: 0,
      hasActiveSession: false,
      checkingSession: false
    }
  },
  created() {
    const recordId = this.$route.params.id
    if (recordId) {
      this.loadResult(recordId)
      this.loadAnswerRecord(recordId)
      this.checkExistingSession()
    }
  },
  methods: {
    async loadResult(recordId) {
      try {
        const response = await getTestResult(recordId)
        if (response.code === 200 && response.data) {
          this.result = response.data
          // 解析维度得分
          if (this.result.dimensionScores) {
            this.dimensionScores = JSON.parse(this.result.dimensionScores)
          }
        }
      } catch (error) {
        console.error('加载测试结果失败:', error)
        this.$message.error('加载结果失败，请重试')
      }
    },
    async loadAnswerRecord(recordId) {
      try {
        const response = await getTestAnswerRecord(recordId)
        if (response.code === 200 && response.data) {
          // 处理题目答案映射
          const answerMap = {}
          if (Array.isArray(response.data.answers)) {
            response.data.answers.forEach(item => {
              // 将字母答案转换为数字（A=1, B=2, C=3, D=4）
              answerMap[item.questionId] = (item.answer.charCodeAt(0) - 64).toString()
            })
          }

          this.test = {
            title: response.data.testTitle,
            questions: response.data.questions
          }
          this.answers = answerMap
          this.testDuration = response.data.duration
        }
      } catch (error) {
        console.error('加载答题记录失败:', error)
        this.$message.error('加载答题记录失败，请重试')
      }
    },
    getDimensionName(key) {
      const dimensionMap = {
        'SOMATIC': '躯体维度',
        'PSYCHOMOTOR': '精神运动维度',
        'COGNITIVE': '认知维度',
        'EMOTIONAL': '情感维度'
      }
      return dimensionMap[key] || key
    },
    formatTime,
    formatDuration,
    backToList() {
      // 获取来源参数
      const from = this.$route.query.from
      // 根据来源返回不同的列表页面
      if (from === 'test-record-list') {
        this.$router.push('/test/test-record-list')
      } else {
        this.$router.push('/test/test-result-list')
      }
    },
    async startAIConsultation() {
      try {
        const recordId = this.$route.params.id
        
        // 先获取所有会话列表
        const { data: sessions } = await getAIChatSessions()
        
        // 查找是否存在与当前测试相关的活跃会话
        const existingSession = sessions.find(session => 
          session.testResultId === this.result.id && 
          session.status === 'ACTIVE'
        )
        
        let targetSession
        if (existingSession) {
          // 如果存在相关会话，直接使用
          targetSession = existingSession
          ElMessage.info('继续之前的咨询会话')
        } else {
          // 不存在则创建新会话，确保传递数字类型的 recordId
          const { data: newSession } = await createAIChatSession(Number(recordId))
          targetSession = newSession
          ElMessage.success('已为您创建AI咨询会话')
        }
        
        // 跳转到会话页面
        this.$router.push({
          path: '/counseling/ai-chat',
          query: { 
            sessionId: targetSession.id.toString(),
            new: !existingSession
          }
        })
      } catch (error) {
        console.error('AI咨询会话操作失败:', error)
        ElMessage.error('操作失败，请重试')
      }
    },
    async checkExistingSession() {
      try {
        this.checkingSession = true
        const { data: sessions } = await getAIChatSessions()
        this.hasActiveSession = sessions.some(session => 
          session.testResultId === this.result.id && 
          session.status === 'ACTIVE'
        )
      } catch (error) {
        console.error('检查已有会话失败:', error)
      } finally {
        this.checkingSession = false
      }
    }
  }
}
</script>

<style scoped>
.test-result {
  padding: 20px;
}
.result-card {
  max-width: 800px;
  margin: 0 auto;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.suggestions {
  white-space: pre-line;
}
.waiting-review {
  margin: 20px 0;
}
.review-info {
  margin-top: 20px;
}
.actions {
  margin-top: 20px;
  text-align: center;
  display: flex;
  justify-content: center;
  gap: 16px;
}
.test-header {
  text-align: center;
  margin-bottom: 20px;
}
.test-info {
  display: flex;
  justify-content: center;
  gap: 20px;
  color: #666;
  margin: 10px 0;
}
.question-list {
  margin: 20px 0;
}
.question-item {
  margin-bottom: 20px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
.question-header {
  margin-bottom: 10px;
}
.question-number {
  font-weight: bold;
  margin-right: 10px;
}
.question-text {
  color: #333;
}
.options-list {
  margin: 10px 0;
  margin-left: 25px;
}
.el-radio {
  margin-right: 30px;
  margin-bottom: 10px;
}
.answer-content {
  margin-left: 25px;
  display: flex;
  gap: 10px;
}
.answer-label {
  color: #666;
  min-width: 80px;
}
.answer-text {
  color: #333;
}
</style> 